<?php
use oxide\plugin\PluginAbstract;
use oxide\http\Context;
use oxide\ui\html;
use oxide\application\View;

define('EMAIL_SUPPORT_PLUGIN_DIR', dirname(__FILE__));

class EmailSupportPlugin extends PluginAbstract
{
	protected
		$subject_list = array(),
		$admin,
		$webmaster,
		$default_sender,
		$permalink;
	
	/**
	 *
	 * @param Context $context 
	 * @notifies 
	 * @listening  CommandInitialize, ModuleContentInfoRenderContentEnd
	 */
	public function onInit(Context $context) 
	{	
		$this->register('CommandInitialize');
		$this->register('ModuleContentInfoRenderContentEnd');
	}
	
	/**
	 * plugin config file checking and setting if not initially set
	 * @param type $event
	 * @param type $sender
	 * @param type $args 
	 */
	public function onCommandInitialize($event, $sender, $args = null)
	{
		$config = $this->getConfig();
		
		// retrieve the confg value for subjects
		$subjects = $config->getSectionValue('emailsupport', 'subjects');
		// check if subjects is not available
		if((bool)$subjects == false) {
			// if true, save default on the plugin config
			$config->setValue('subjects', 'webmaster:l.joyce@alifsoft.com,admin:l.joyce@alifsoft.com', 'emailsupport');
			$config->save();
		} else {
			// if exists, then store the values
			$subject_items = explode(',', $subjects);
			// store the various values into the subject list
			foreach($subject_items as $subject_item)
			{
				$item = explode(':', $subject_item);
				// where item[0] is the key, item[1] is the value
				$this->subject_list[$item[0]] = $item[1];
			}
		}
		
		// retrieve the config value for default_sender from the emailsupport section
		$default_sender = $config->getSectionValue('emailsupport', 'default_sender');
		// check if default_sender is not available
		if((bool)$default_sender == false) {
			// if true, save default on the plugin config
			$config->setValue('default_sender', 'admin@alifsoft.com', 'emailsupport');
			$config->save();
		} else {
			// if exists, then store the values
			$this->default_sender = $default_sender;
		}
		
		// retrieve the config value for permalink from the emailsupport section
		$permalink = $config->getSectionValue('emailsupport', 'permalink');
		// check if permalink is not available
		if((bool)$permalink == false) {
			// if true, save default on the plugin config
			$config->setValue('permalink', 'page/contact-us.html', 'emailsupport');
			$config->save();
		} else {
			// if exists, then store the values
			$this->permalink = $permalink;
		}

	}
	
	/**
	 * render the contact form based on the user specified permalink
	 * @param type $event
	 * @param type $sender
	 * @param type $content 
	 */
	public function onModuleContentInfoRenderContentEnd($event, $sender, $content) 
	{
		// initialize vars
		\oxide\application\View::load('_html');
		$context = $this->_context;
		$route = $this->getContext()->route;
		
		// split up the user defined permalink
		if (!empty($this->permalink)) {
			$peramlink = explode('/', $this->permalink);
		}
		
		// if page view is on the user defined peramlink, display the form
		if ($route->params[0] == $peramlink[0] && $route->params[1] == $peramlink[1]) {
			$this->contactForm();
		}
		
	}
	
	/**
	 * contact form 
	 */
	protected function contactForm()
   {
		include 'SupportForm.php';
		
		// Create contact form
		$form = new SupportForm();
		
		$subject_keys = array_keys($this->subject_list);
		foreach($subject_keys as $subject_key)
		{
			$subjects[$subject_key] = $subject_key;
		}
		
		// setup form and add additional message field
		$form->setup($subjects);
		$form->addControl(new html\TextareaControl('message', null, 'Message:'));
		
		// validator container and add additional validations
		$validatorContainer = $form->getInputValidation()->getValidatorContainer();
		$validatorContainer->addRequired('message');
		
		// check if form is submitted
      if ($form->isSubmit()) {
			
			$result = null;
			$values = $form->process($result);
			
			// check if form is valid
         if($result->isValid()) {
				// if true, intialize
				$fullname = $values['fullname'];
				$email = $values['email'];
				$subject = $values['subject'];
				$message = $values['message'];
				
				// check if the subject is valid against the subject list
				// if not, set it to default which is sent to default
				if (array_key_exists($subject, $this->subject_list)) {
					$subject_email = $this->subject_list[$subject];
				}
				
				// send email to specific subject
				$sent_from = $this->default_sender;
				$sent_to = array('to' => $subject_email);
				$sent_subject = $subject;
				$sent_message = $message;
				$success = oxide\util\Mailer::send($sent_from, $sent_to, $sent_subject, $sent_message);
				
				if ($success) {
					// send confirmation email to sender
					$confirmation_from = $this->default_sender;
					$confirmation_to = array('to' => $email);
					$confirmation_subject = "Confirmation of your message";
					$confirmation_message = "This is a confirmation to assure that we have received your message. Thank you.";
					oxide\util\Mailer::send($confirmation_from, $confirmation_to, $confirmation_subject, $confirmation_message);
				}
				
				// reset the form after sucessful submission
				$form->reset();
				
			} else {
            $view->errors = $result->getErrors();
         }
		}
      $vscript = EMAIL_SUPPORT_PLUGIN_DIR . '/emailsupport.phtml';
		$view = new View($vscript);
		$view->assign('form', $form);
		$view->form = $form;
		echo $view->render();
   }

}
?>